import { computed, ref } from 'vue';

import { Menu } from '/@/router/types';
import { usePermissionStoreWithOut } from '../../store/modules/permission';
import { storeToRefs } from 'pinia';
import { router } from '/@/router/index';
const permissionStore = usePermissionStoreWithOut();
const menu = storeToRefs(permissionStore).backMenuList;
const getCurrentPath = computed(() => router.currentRoute.value.path);

// get the sub children of current routes to render tabList
const tabList = ref<Menu[]>([]);
const parentTitle = ref<string>('');
export const getTabList = (currentPath: string) => {
  let gotTargetRoute = false;
  const wideTraverse = function (menu: Menu, key: string) {
    if (menu !== null) {
      const queue: Menu[] = [];
      queue.unshift(menu);
      while (queue.length != 0) {
        const item = queue.shift();
        if (item?.path === key) {
          gotTargetRoute = true;
        }
        if (!item?.children) {
          tabList.value.push(item as Menu);
        } else {
          const children = item?.children;
          for (let i = 0; i < children.length; i++) {
            queue.push(children[i]);
          }
        }
      }
    }
  };

  for (let i = 0; i < menu.value.length; i++) {
    if (!gotTargetRoute) {
      tabList.value = [];
      parentTitle.value = menu.value[i].title;
      wideTraverse(menu.value[i], currentPath);
    }
  }
  return tabList.value;
};

export function useUserSetting() {
  return {
    getTabList,
    getCurrentPath,
    parentTitle,
    tabList,
  };
}
